package com.banciyuan.bcywebview.base.app;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.multidex.MultiDexApplication;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.baidu.mobstat.StatService;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.helper.data.DataCenter;
import com.banciyuan.bcywebview.base.helper.push.PushDataHelper;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

//自定义的Application，初始化了图片2级缓存，网络接口，greendao，社会化分享，统计插件（包括百度和bugly）
public class BaseApplication extends MultiDexApplication {

    private int appCount = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void getVersion() {
        try {
            PackageManager pm = getApplicationContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(getApplicationContext().getPackageName(), 0);
            StringRequestParam.version_name = pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void init() {
        FixNoClassDefFoundError81083();
        getVersion();
        getStates();
        initHttp();
        initData();
        initUser();
        initPush();
        initWeibo();
        initBuglyUpdate();
        initBugly();
        initBaidu();
        initImageLoader();
    }

    private void initWeibo() {
        WbSdk.install(this, new AuthInfo(this, HttpUtils.getWeibo(), MyConstants.REDIRECT_URL, MyConstants.SINA_SCOPE));
    }

    private void initHttp() {
        HttpUtils.initInterface();
    }

    private void getStates() {
        this.registerActivityLifecycleCallbacks(new ActivityLifeCycleCallBackImpl() {
            @Override
            public void onActivityStarted(Activity activity) {
                appCount++;
            }

            @Override
            public void onActivityStopped(Activity activity) {
                appCount--;
            }
        });
    }


    private void initPush() {
        final PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setDebugMode(false);
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String registrationId) {
                SPHelper.putString(BaseApplication.this, SPConstant.SPNAME_DEVICES, SPConstant.TOKEN, registrationId);
            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });

        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {

            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                PushDataHelper.processPushData(context, msg.custom);
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
    }

    private void initBugly() {
        try {
            CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(getApplicationContext()); //App的策略Bean
            ApplicationInfo appInfo = this.getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            String qqChannel = appInfo.metaData.getString("QQCrash_CHANNEL");
            if (!TextUtils.isEmpty(qqChannel)) strategy.setAppChannel(qqChannel);     //设置渠道
            else strategy = null;
            if (strategy == null) {
                Bugly.init(this, MyConstants.CRASH_APP_ID, false);
            } else {
                Bugly.init(this, MyConstants.CRASH_APP_ID, false, strategy);
            }
            TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
            String imei = telephonyManager.getDeviceId();
            if (!TextUtils.isEmpty(imei)) {
                CrashReport.setUserId(imei);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initBuglyUpdate() {
        Beta.autoCheckUpgrade = false;
        Beta.canShowApkInfo = true;
        Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog;
        Beta.tipsDialogLayoutId = R.layout.tip_dialog;
    }

    private void initBaidu() {
        StatService.setDebugOn(false);
    }

    private void initImageLoader() {
        ImageOptions.init(this);
    }


    private void initData() {
        DataCenter.getInstance();
    }

    private void initUser() {
    }

    private void FixNoClassDefFoundError81083() {
        try {
            Class.forName("android.os.AsyncTask");
        } catch (Throwable ignore) {
        }
    }

    public boolean isAppRunningInFront() {
        return appCount > 0;
    }


}